package com.example.governmentcrawler.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.LinkedHashMap;

/**
 * @projectName: GovernmentCrawler
 * @package: com.example.governmentcrawler.utils
 * @className: FileSup
 * @author: xxXPCSC
 * @description: TODO
 * @date: 2024/3/21 19:19
 * @version: 1.0
 **/
@Component
public class FileSup {
    private String baseFolder="./TxtFiles";
    private String LastEmailSendJson="lastSend.json";
    private String StateTxt = "state.txt";
    private String filePath = baseFolder+"/"+LastEmailSendJson;
    private String statePath = baseFolder+"/"+StateTxt;

    public void folderExist(){
        File folder = new File(baseFolder);
        if (!folder.exists()) {
            boolean created = folder.mkdir();
        } else {
            System.out.println("文件夹 " + baseFolder + " 已经存在。");
        }
    }

    public Boolean fileExist(){
        folderExist();

        File file = new File(filePath);
        if (file.exists()) {
            System.out.println("文件 " + filePath + " 已经存在。");
            return true;
        }
        else {
            try {
                boolean created = file.createNewFile();
                if (created) {
                    System.out.println("文件 " + filePath + " 不存在，已成功创建。");
                } else {
                    System.out.println("文件 " + filePath + " 不存在，创建失败。");
                }
            } catch (IOException e) {
                System.err.println("创建文件时出现异常：" + e.getMessage());
            }
        }
        //无论创建成功与否都返回false
        return false;
    }

    public Boolean stateExist(){
        folderExist();
        File file = new File(statePath);
        if (file.exists()) {
            System.out.println("文件 " + statePath + " 已经存在。");
            return true;
        }
        else {
            try {
                boolean created = file.createNewFile();
                if (created) {
                    System.out.println("文件 " + statePath + " 不存在，已成功创建。");
                } else {
                    System.out.println("文件 " + statePath + " 不存在，创建失败。");
                }
            } catch (IOException e) {
                System.err.println("创建文件时出现异常：" + e.getMessage());
            }
        }
        //无论创建成功与否都返回false
        return false;
    }

    public Boolean WritInFile(LinkedHashMap<String, String> tempMap){
        String json = JSON.toJSONString(tempMap, SerializerFeature.PrettyFormat);
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(json);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public LinkedHashMap<String, String>  ReadForFile(){
        LinkedHashMap<String,String>  maps = new LinkedHashMap<>();
        if(!fileExist())
            return null;
        try (FileReader fileReader = new FileReader(filePath)) {
            // 从 JSON 文件读取内容并转换为 Map 对象
            Reader reader = new InputStreamReader(new FileInputStream(filePath), "Utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            String jsonStr = sb.toString();

            maps = JSON.parseObject(jsonStr,LinkedHashMap.class);
            // 打印读取的 Map 对象
            System.out.println("从 JSON 文件读取的 Map 对象: " + maps);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return maps;
    }

    public int ReadForState(){
        int state = 0;
        if(!stateExist())
            return 0;
        try (FileReader fileReader = new FileReader(statePath)) {
            // 从 JSON 文件读取内容并转换为 Map 对象
            Reader reader = new InputStreamReader(new FileInputStream(statePath), "Utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            String numberStr = sb.toString();
            state = Integer.parseInt(numberStr);
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
        return state;
    }

    public void WritInState(int state){
        String json = String.valueOf(state);
        try (FileWriter fileWriter = new FileWriter(statePath)) {
            fileWriter.write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
